package com.janko.redislock.redisLock.controller.scenes;


import io.swagger.annotations.Api;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = {"秒杀"}, description = "redis的秒杀接口")
@RestController
public class ReduceController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/reduce", method = RequestMethod.GET)
    public String redureGood() {
        String goodKey = "iphone";
        String lockKey = "lockKey";

        String clientId = String.valueOf(UUID.randomUUID());
        try {
            /**设置30秒的分布式锁 该时间段内，单线程执行 即:setNx的方法使用*/
            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 10, TimeUnit.SECONDS);
            if (!result) {
                /** 加锁失败  上个程序还是结束.*/
                return "网络繁忙，请稍后再试";
            }
            int num = Integer.parseInt(stringRedisTemplate.opsForValue().get(goodKey));
            if (num > 0) {
                int real_num = num - 1;
                stringRedisTemplate.opsForValue().set(goodKey, real_num + "");
                System.out.println("扣减成功，剩余库存：" + real_num);
            } else
                System.out.println("扣减失败，库存不足了：" + num);
        } finally {
            if (clientId.equals(stringRedisTemplate.opsForValue().get(lockKey)))
                stringRedisTemplate.delete(lockKey);
        }
        return "success";
    }


    @Autowired
    private Redisson redisson;

    /**
     * @Author: Janko
     * @Description: 使用redis分布式锁版本  Redisson
     * @Date: 2020/6/21  17:30
     * @Return 返回是否执行成功
     */
    @RequestMapping(value = "/reduce2", method = RequestMethod.GET)
    public String redureGoodRedisson() {
        String goodKey = "iphone";
        String lockKey = "lockKey";

        RLock redissonLock = redisson.getLock(lockKey);
        try {
            redissonLock.lock();
            int num = Integer.parseInt(stringRedisTemplate.opsForValue().get(goodKey));
            if (num > 0) {
                int real_num = num - 1;
                stringRedisTemplate.opsForValue().set(goodKey, real_num + "");
                System.out.println("扣减成功，剩余库存：" + real_num);
            } else
                System.out.println("扣减失败，库存不足了：" + num);
        } finally {
            redissonLock.unlock();
        }
        return "success";
    }
}
